<template>
  <div class="department-management">
    <!-- Operation Buttons -->
    <el-row class="mb-4">
      <el-col :span="24" class="text-right">
        <el-button type="primary" @click="handleAdd">新增部门</el-button>
      </el-col>
    </el-row>

    <!-- Department Table -->
    <el-table :data="departmentList" border row-key="id">
      <el-table-column prop="name" label="部门名称" width="180" />
      <el-table-column prop="address" label="部门地址" />
      <el-table-column prop="phone" label="部门电话" width="120" />
      <el-table-column prop="leader" label="负责人" width="120" />
      <el-table-column prop="remark" label="备注" />
      <el-table-column prop="parentname" label="上级部门" width="150" />
      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row.id)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- Add/Edit Dialog -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑部门' : '新增部门'">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="部门地址" prop="address">
          <el-input v-model="form.address" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="负责人" prop="leader">
          <el-input v-model="form.leader" />
        </el-form-item>
        <el-form-item label="上级部门" prop="parentid">
          <el-tree-select
            v-model="form.parentid"
            :data="departmentOptions"
            check-strictly
            :props="{ label: 'name', value: 'id' }"
            placeholder="请选择上级部门"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed,onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from '@/utils/request.js'
// 初始化加载
onMounted(() => {
    selectAllInfos()
})
// Mock data
const mockDepartments = [
  // { id: 1, name: '总公司', parentId: null },
  // { id: 2, name: '技术部', parentId: 1, address: 'A座101', phone: '010-12345678', leader: '张三' },
  // { id: 3, name: '市场部', parentId: 1, address: 'A座102', phone: '010-87654321', leader: '李四' }
]

const departmentList = ref()
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)

const form = reactive({
  id: null,
  name: '',
  address: '',
  phone: '',
  leader: '',
  parentid: null,
  remark: ''
})

const rules = {
  name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
  address: [{ required: true, message: '请输入部门地址', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  leader: [{ required: true, message: '请输入负责人', trigger: 'blur' }]
}

// 部门树据
const departmentOptions = ref([])


const generateTree = (departments, parentId = null) => {
  return departments
    .filter(item => item.parentId === parentId)
    .map(item => ({
      ...item,
      children: generateTree(departments, item.id)
    }))
}

const handleAdd = () => {
  //加载部门树
  selectOrgTree()

  isEdit.value = false
  Object.assign(form, {
    id: null,
    name: '',
    address: '',
    phone: '',
    leader: '',
    parentId: null,
    remark: ''
  })
  dialogVisible.value = true
}

const handleEdit = (id) => {
  isEdit.value = true
  dialogVisible.value = true
  //  加载部门树
  selectOrgTree()
  //根据id查找部门信息,并将数据传输到表单中
  axios(
            {
              url: '/org/getInfoById.do',
              method: 'post',
              params: {
                id: id
              },
            }).then((res) => {
              form.id = res.id
              form.name = res.name
              form.address = res.address
              form.phone = res.phone
              form.leader = res.leader
              form.parentid = res.parentid
              form.remark = res.remark
            })
}


const handleDelete = async (id) => {
  //删除数据
  axios({
    url: '/org/deleteInfo.do',
    method: 'post',
    params: {
      id: id
    },
  }).then((res) => {
    if (res.result == 'success') {
      ElMessage.success('删除成功!')
      selectAllInfos()
    } else {
      ElMessage.error('删除失败，请检查数据是否正确!')
    }
  })



}

const submitForm = async () => {
  await formRef.value.validate()
  
  if (isEdit.value) {
   //编辑部门信息
    axios(
            {
              url: '/org/saveOrUpdateInfo.do',
              method: 'post',
              params: {
                  id:form.id,
                  name:form.name,
                  address:form.address,
                  phone:form.phone,
                  leader:form.leader,
                  parentid:form.parentid,
                  remark:form.remark
              },
            }).then((res) => {
              if(res.result=='success'){
                 ElMessage.success('修改成功!');
                 dialogVisible.value = false
                  selectAllInfos()
              }else {
                ElMessage.error('修改失败，请检查数据是否正确!');
              }
            }).catch((error) => {
               ElMessage.error('网络请求失败，请检查网络是否畅通!');
            })
  } else {
    //保存部门信息
    axios(
            {
              url: '/org/saveOrUpdateInfo.do',
              method: 'post',
              params: {
                  name:form.name,
                  address:form.address,
                  phone:form.phone,
                  leader:form.leader,
                  parentid:form.parentid,
                  remark:form.remark
              },
            }).then((res) => {
              if(res.result=='success'){
                 ElMessage.success('保存成功!');
                 dialogVisible.value = false
                  selectAllInfos()
              }else {
                ElMessage.error('保存失败，请检查数据是否正确!');
              }
            }).catch((error) => {
               ElMessage.error('网络请求失败，请检查网络是否畅通!');
            })
  }
}
//  获取部门信息
const selectAllInfos = () => {
    axios(
            {
              url: '/org/selectAllInfos.do',
              method: 'post',
              params: {
              },
            }).then((res) => {
                // alert(JSON.stringify(res))
                departmentList.value=res
            }).catch((error) => {
                 ElMessage.error('网络请求失败，请检查网络是否畅通!');
            })
}
//  获取部门树
const selectOrgTree = () => {
    axios(
            {
              url: '/org/selectOrgTree.do',
              method: 'post',
              params: {
              },
            }).then((res) => {
                // alert(JSON.stringify(res))
                departmentOptions.value=res
            }).catch((error) => {
                 ElMessage.error('网络请求失败，请检查网络是否畅通!');
            })
}
</script>

<style scoped>
.department-management {
  padding: 20px;
}
</style>